// 管理员功能模块
class AdminManager {
    constructor() {
        this.isAdmin = false;
        this.adminPanel = null;
        this.adminToggleBtn = null;
        this.kickModal = null;
        this.currentKickTarget = null;
        this.onlineUsers = [];
        this.searchTimeout = null;

        this.init();
    }

    getCurrentSessionId() {
        // 尝试多种方式获取会话ID
        if (typeof sessionId !== 'undefined' && sessionId) {
            return sessionId;
        }
        if (typeof window.sessionId !== 'undefined' && window.sessionId) {
            return window.sessionId;
        }
        // 从WebSocket获取
        if (typeof websocket !== 'undefined' && websocket) {
            if (websocket.url) {
                const match = websocket.url.match(/sessionId=([^&]*)/);
                if (match) {
                    return decodeURIComponent(match[1]);
                }
            }
            // 如果是SockJS连接，会话ID就是WebSocket的ID
            if (websocket._transport && websocket._transport.url) {
                const urlParts = websocket._transport.url.split('/');
                const sessionPart = urlParts[urlParts.length - 2];
                if (sessionPart && sessionPart.length > 5) {
                    return sessionPart;
                }
            }
            // 直接从WebSocket对象获取
            if (websocket.id) {
                return websocket.id;
            }
        }
        // 从全局变量获取
        if (typeof getSessionId === 'function') {
            return getSessionId();
        }
        return null;
    }

    init() {
        this.createAdminUI();
        this.setupEventListeners();
        this.checkAdminStatus();
    }

    createAdminUI() {
        // 延迟获取在线用户按钮，确保DOM已加载
        this.bindOnlineUsersButton();

        // 创建管理员切换按钮（只有管理员可见）
        this.adminToggleBtn = document.createElement('button');
        this.adminToggleBtn.className = 'admin-toggle-btn hidden';
        this.adminToggleBtn.innerHTML = '<i class="fas fa-cog"></i>';
        this.adminToggleBtn.title = '管理员面板';
        document.body.appendChild(this.adminToggleBtn);

        // 创建在线用户弹窗（微信风格）
        const adminPanelHTML = `
            <div id="onlineUsersModal" class="online-users-modal">
                <div class="modal-overlay" id="modalOverlay"></div>
                <div class="modal-container">
                    <div class="modal-header">
                        <h3 id="modalTitle">在线用户</h3>
                        <button class="close-btn" id="closeModalBtn">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <div class="modal-search">
                        <div class="search-box">
                            <i class="fas fa-search"></i>
                            <input type="text" id="userSearchInput" placeholder="搜索">
                        </div>
                    </div>
                    <div class="modal-body">
                        <div class="users-list" id="usersList">
                            <div class="loading-state">
                                <i class="fas fa-spinner fa-spin"></i>
                                <span>加载中...</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;

        // 创建踢出确认对话框
        const kickModalHTML = `
            <div id="kickModal" class="kick-modal">
                <div class="kick-modal-content">
                    <div class="kick-modal-header">
                        <h3>确认踢出用户</h3>
                        <p id="kickTargetName">确定要踢出用户吗？</p>
                    </div>
                    <div class="kick-reason">
                        <label for="kickReasonInput">踢出原因 (可选):</label>
                        <textarea id="kickReasonInput" placeholder="请输入踢出原因..."></textarea>
                    </div>
                    <div class="kick-modal-actions">
                        <button class="kick-modal-btn cancel" id="kickCancelBtn">取消</button>
                        <button class="kick-modal-btn confirm" id="kickConfirmBtn">确认踢出</button>
                    </div>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', adminPanelHTML + kickModalHTML);

        this.onlineUsersModal = document.getElementById('onlineUsersModal');
        this.kickModal = document.getElementById('kickModal');
    }

    bindOnlineUsersButton() {
        // 使用更可靠的方式绑定按钮事件
        const bindButton = () => {
            this.onlineUsersBtn = document.getElementById('onlineUsersBtn');
            if (this.onlineUsersBtn) {
                console.log('找到在线用户按钮，绑定点击事件');
                this.onlineUsersBtn.addEventListener('click', (e) => {
                    console.log('在线用户按钮被点击');
                    e.preventDefault();
                    this.showOnlineUsersModal();
                });
                return true;
            }
            return false;
        };

        // 立即尝试绑定
        if (!bindButton()) {
            // 如果立即绑定失败，等待DOM加载
            let attempts = 0;
            const maxAttempts = 50; // 最多尝试5秒
            const interval = setInterval(() => {
                attempts++;
                if (bindButton() || attempts >= maxAttempts) {
                    clearInterval(interval);
                    if (attempts >= maxAttempts) {
                        console.error('无法找到在线用户按钮，已达到最大尝试次数');
                        // 尝试查找所有可能的按钮
                        const allButtons = document.querySelectorAll('button');
                        console.log('页面上的所有按钮:', Array.from(allButtons).map(btn => ({
                            id: btn.id,
                            class: btn.className,
                            title: btn.title
                        })));
                    }
                }
            }, 100);
        }
    }

    setupEventListeners() {
        // 管理员面板切换（只有管理员可以使用）
        this.adminToggleBtn.addEventListener('click', () => {
            this.showOnlineUsersModal();
        });

        // 关闭弹窗
        document.getElementById('closeModalBtn').addEventListener('click', () => {
            this.hideOnlineUsersModal();
        });

        // 点击遮罩关闭
        document.getElementById('modalOverlay').addEventListener('click', () => {
            this.hideOnlineUsersModal();
        });

        // 搜索功能
        document.getElementById('userSearchInput').addEventListener('input', (e) => {
            this.handleSearch(e.target.value);
        });

        // 踢出对话框事件
        document.getElementById('kickCancelBtn').addEventListener('click', () => {
            this.hideKickModal();
        });

        document.getElementById('kickConfirmBtn').addEventListener('click', () => {
            this.confirmKickUser();
        });

        // 点击模态框外部关闭
        this.kickModal.addEventListener('click', (e) => {
            if (e.target === this.kickModal) {
                this.hideKickModal();
            }
        });

        // ESC键关闭
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                if (this.kickModal.classList.contains('show')) {
                    this.hideKickModal();
                } else if (this.adminPanel.classList.contains('show')) {
                    this.hideAdminPanel();
                }
            }
        });
    }

    checkAdminStatus() {
        // 延迟检查，确保sessionId已经设置，并且用户已经加入聊天
        setTimeout(() => {
            const joinedChat = window.hasJoinedChat || (typeof hasJoinedChat !== 'undefined' && hasJoinedChat);
            if (sessionId && joinedChat) {
                this.requestOnlineUsers();
            }
        }, 1000);
    }

    showAdminButton() {
        this.isAdmin = true;
        this.adminToggleBtn.classList.remove('hidden');
    }

    hideAdminButton() {
        this.isAdmin = false;
        this.adminToggleBtn.classList.add('hidden');
        // this.hideOnlineUsersModal();
    }

    showOnlineUsersModal() {
        console.log('showOnlineUsersModal被调用');

        // 简化权限检查 - 只检查是否有基本的连接状态
        const currentSessionId = this.getCurrentSessionId();
        const joinedChat = window.hasJoinedChat ||
                          (typeof hasJoinedChat !== 'undefined' && hasJoinedChat) ||
                          (typeof currentNickname !== 'undefined' && currentNickname && currentNickname.trim() !== '');

        console.log('状态检查:', {
            'sessionId': currentSessionId,
            'joinedChat': joinedChat,
            'currentNickname': typeof currentNickname !== 'undefined' ? currentNickname : 'undefined'
        });

        // 如果完全没有任何状态，才提示错误
        if (!joinedChat && !currentSessionId && (typeof currentNickname === 'undefined' || !currentNickname)) {
            this.showError('请先加入聊天室');
            return;
        }

        // 更新标题
        const modalTitle = document.getElementById('modalTitle');
        if (modalTitle) {
            modalTitle.textContent = this.isAdmin ? '在线用户管理' : '在线用户';
        }

        this.onlineUsersModal.classList.add('show');
        document.body.style.overflow = 'hidden'; // 防止背景滚动
        this.requestOnlineUsers();
    }

    hideOnlineUsersModal() {
        this.onlineUsersModal.classList.remove('show');
        document.body.style.overflow = ''; // 恢复背景滚动
    }

    requestOnlineUsers() {
        // 使用REST API获取在线用户列表
        // 获取当前会话ID
        const currentSessionId = this.getCurrentSessionId();
        console.log('请求在线用户列表，sessionId:', currentSessionId);
        console.log('window.sessionId:', window.sessionId);
        console.log('全局sessionId:', typeof sessionId !== 'undefined' ? sessionId : 'undefined');

        // 如果没有sessionId，使用备用方案
        const finalSessionId = currentSessionId || (typeof getSessionId === 'function' ? getSessionId() : 'temp-session-' + Date.now());

        fetch('/api/admin/online-users?sessionId=' + encodeURIComponent(finalSessionId))
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                this.handleOnlineUsersResponse(data.data);
                // 检查当前用户是否为管理员
                if (data.isAdmin) {
                    this.showAdminButton();
                } else {
                    this.hideAdminButton();
                }
            } else {
                this.showError(data.message);
            }
        })
        .catch(error => {
            this.showError('获取在线用户列表失败: ' + error.message);
        });
    }

    handleOnlineUsersResponse(users) {
        this.onlineUsers = users;
        this.renderOnlineUsers(users);
    }

    renderOnlineUsers(users) {
        const container = document.getElementById('usersList');

        if (!users || users.length === 0) {
            container.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-user-friends"></i>
                    <span>暂无在线用户</span>
                </div>
            `;
            return;
        }

        const currentSessionId = this.getCurrentSessionId();
        const usersHTML = users.map(user => {
            const isCurrentUser = user.sessionId === currentSessionId;
            const isAdmin = user.userType === 'ADMIN';

            return `
                <div class="user-item" data-session-id="${user.sessionId}">
                    <div class="user-avatar">
                        <i class="fas fa-user${isAdmin ? '-shield' : ''}"></i>
                    </div>
                    <div class="user-info">
                        <div class="user-name">
                            ${user.nickname}
                            ${isCurrentUser ? '<span class="current-user">（我）</span>' : ''}
                            ${isAdmin ? '<span class="admin-badge">管理员</span>' : ''}
                        </div>
<!--                        <div class="user-status">-->
<!--                            <span class="online-dot"></span>-->
<!--                            在线-->
<!--                        </div>-->
                    </div>
                    ${!isCurrentUser && this.isAdmin ? `
                        <div class="user-actions">
                            ${!isAdmin ? `
                                <button class="action-btn kick-btn" onclick="adminManager.showKickModal('${user.sessionId}', '${user.nickname}')">
                                    <i class="fas fa-user-times"></i> 移除
                                </button>
                                <button class="action-btn ban-btn" onclick="adminManager.showBanModal('${user.sessionId}', '${user.nickname}')">
                                    <i class="fas fa-user-slash"></i> 禁言
                                </button>
                                <button class="action-btn promote-btn" onclick="adminManager.promoteUser('${user.sessionId}', '${user.nickname}')">
                                    <i class="fas fa-crown"></i> 设为管理员
                                </button>
                            ` : ''}
                        </div>
                    ` : ''}
                </div>
            `;
        }).join('');

        container.innerHTML = usersHTML;
    }

    handleSearch(query) {
        if (this.searchTimeout) {
            clearTimeout(this.searchTimeout);
        }

        this.searchTimeout = setTimeout(() => {
            const filteredUsers = this.onlineUsers.filter(user =>
                user.nickname.toLowerCase().includes(query.toLowerCase())
            );
            this.renderOnlineUsers(filteredUsers);
        }, 300);
    }

    showKickModal(targetSessionId, targetNickname) {
        this.currentKickTarget = { sessionId: targetSessionId, nickname: targetNickname };
        document.getElementById('kickTargetName').textContent = `确定要踢出用户 "${targetNickname}" 吗？`;
        document.getElementById('kickReasonInput').value = '';
        this.kickModal.classList.add('show');
    }

    hideKickModal() {
        this.kickModal.classList.remove('show');
        this.currentKickTarget = null;
    }

    showBanModal(targetSessionId, targetNickname) {
        this.currentBanTarget = { sessionId: targetSessionId, nickname: targetNickname };
        
        // 创建禁言模态框（如果不存在）
        if (!this.banModal) {
            this.createBanModal();
        }
        
        document.getElementById('banTargetName').textContent = `确定要禁言用户 "${targetNickname}" 吗？`;
        document.getElementById('banReasonInput').value = '';
        document.getElementById('banDurationInput').value = '24';
        this.banModal.classList.add('show');
    }

    hideBanModal() {
        if (this.banModal) {
            this.banModal.classList.remove('show');
        }
        this.currentBanTarget = null;
    }

    createBanModal() {
        // 创建禁言模态框HTML
        const banModalHTML = `
            <div class="kick-modal" id="banModal">
                <div class="kick-modal-content">
                    <div class="kick-modal-header">
                        <h3><i class="fas fa-user-slash"></i> 禁言用户</h3>
                        <p id="banTargetName">确定要禁言该用户吗？</p>
                    </div>
                    <div class="kick-reason">
                        <label for="banReasonInput">禁言原因：</label>
                        <textarea id="banReasonInput" placeholder="请输入禁言原因..."></textarea>
                    </div>
                    <div class="kick-reason">
                        <label for="banDurationInput">禁言时长（小时，留空为永久禁言）：</label>
                        <input type="number" id="banDurationInput" min="1" max="8760" placeholder="24" />
                    </div>
                    <div class="kick-modal-actions">
                        <button class="kick-modal-btn cancel" onclick="adminManager.hideBanModal()">
                            <i class="fas fa-times"></i> 取消
                        </button>
                        <button class="kick-modal-btn confirm" onclick="adminManager.confirmBanUser()">
                            <i class="fas fa-user-slash"></i> 确认禁言
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        // 添加到页面
        document.body.insertAdjacentHTML('beforeend', banModalHTML);
        this.banModal = document.getElementById('banModal');
        
        // 添加点击外部关闭功能
        this.banModal.addEventListener('click', (e) => {
            if (e.target === this.banModal) {
                this.hideBanModal();
            }
        });
    }

    confirmBanUser() {
        if (!this.currentBanTarget) return;

        const reason = document.getElementById('banReasonInput').value.trim() || '违规行为';
        const durationInput = document.getElementById('banDurationInput').value.trim();
        let banHours = null;
        
        if (durationInput && durationInput !== '') {
            banHours = parseInt(durationInput);
            if (isNaN(banHours) || banHours <= 0) {
                alert('禁言时长必须是正整数');
                return;
            }
        }

        const message = {
            type: 'ADMIN_BAN_USER',
            senderNickname: currentNickname,
            content: reason,
            targetSessionId: this.currentBanTarget.sessionId,
            banHours: banHours,
            timestamp: new Date().toISOString()
        };

        if (websocket && websocket.readyState === WebSocket.OPEN) {
            websocket.send(JSON.stringify(message));
            this.hideBanModal();
        } else {
            this.showError('WebSocket连接未建立');
        }
    }

    confirmKickUser() {
        if (!this.currentKickTarget) return;

        const reason = document.getElementById('kickReasonInput').value.trim();

        const message = {
            type: 'ADMIN_KICK_USER',
            senderNickname: currentNickname,
            content: reason,
            targetSessionId: this.currentKickTarget.sessionId,
            timestamp: new Date().toISOString()
        };

        if (websocket && websocket.readyState === WebSocket.OPEN) {
            websocket.send(JSON.stringify(message));
            this.hideKickModal();
        } else {
            this.showError('WebSocket连接未建立');
        }
    }

    promoteUser(targetSessionId, targetNickname) {
        if (!confirm(`确定要将用户 "${targetNickname}" 设置为管理员吗？`)) {
            return;
        }

        fetch('/api/admin/set-admin', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                adminSessionId: sessionId,
                targetSessionId: targetSessionId
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                this.showSuccess(data.message);
                this.requestOnlineUsers(); // 刷新用户列表
            } else {
                this.showError(data.message);
            }
        })
        .catch(error => {
            this.showError('设置管理员失败: ' + error.message);
        });
    }

    handleAdminOperationResult(message) {
        if (message.operationResult) {
            this.showSuccess(message.content);
            this.requestOnlineUsers(); // 刷新用户列表
        } else {
            this.showError(message.content);
        }
    }

    handleKickMessage() {
        // 当前用户被踢出时的处理
        this.showError('您已被管理员踢出聊天室');
        setTimeout(() => {
            location.reload();
        }, 3000);
    }

    showSuccess(message) {
        this.showNotification(message, 'success');
    }

    showError(message) {
        this.showNotification(message, 'error');
    }

    showNotification(message, type = 'success') {
        const notification = document.createElement('div');
        notification.className = `admin-notification ${type}`;
        notification.textContent = message;

        document.body.appendChild(notification);

        // 显示动画
        setTimeout(() => {
            notification.classList.add('show');
        }, 100);

        // 自动隐藏
        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
        }, 3000);
    }
}

// 创建全局管理员管理器实例
let adminManager;

// 页面加载完成后初始化管理员功能
document.addEventListener('DOMContentLoaded', function() {
    adminManager = new AdminManager();
});

// 添加全局测试函数
window.testOnlineUsers = function() {
    console.log('测试在线用户功能...');
    if (window.adminManager) {
        window.adminManager.showOnlineUsersModal();
    } else if (adminManager) {
        adminManager.showOnlineUsersModal();
    } else {
        console.error('adminManager未初始化');
    }
};

// 全局按钮点击处理函数
window.handleOnlineUsersClick = function(event) {
    console.log('HTML onclick被触发');
    event.preventDefault();
    event.stopPropagation();

    if (window.adminManager) {
        window.adminManager.showOnlineUsersModal();
    } else if (typeof adminManager !== 'undefined' && adminManager) {
        adminManager.showOnlineUsersModal();
    } else {
        console.error('adminManager未找到，尝试直接创建');
        // 作为最后的备用方案，尝试直接创建
        setTimeout(() => {
            if (typeof AdminManager !== 'undefined') {
                const tempManager = new AdminManager();
                tempManager.showOnlineUsersModal();
            }
        }, 100);
    }
};

// 添加全局按钮点击处理器作为备用方案
document.addEventListener('DOMContentLoaded', function() {
    setTimeout(() => {
        const onlineUsersBtn = document.getElementById('onlineUsersBtn');
        if (onlineUsersBtn) {
            // 移除可能存在的旧事件监听器
            onlineUsersBtn.onclick = null;

            // 添加新的点击事件
            onlineUsersBtn.addEventListener('click', function(e) {
                console.log('全局按钮点击处理器被触发');
                e.preventDefault();
                if (window.adminManager) {
                    window.adminManager.showOnlineUsersModal();
                } else if (typeof adminManager !== 'undefined') {
                    adminManager.showOnlineUsersModal();
                } else {
                    console.error('adminManager未找到');
                }
            });
            console.log('全局按钮点击处理器已设置');
        } else {
            console.warn('未找到在线用户按钮');
        }
    }, 1000);
});

// 导出给其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = AdminManager;
}
